<template>
  <div>
    <h2>订单管理</h2>
    <el-card>
      <div style="margin-bottom: 16px; display: flex; gap: 12px;">
        <el-button type="primary" @click="openAddDialog">新建订单</el-button>
        <el-select v-model="search.status" placeholder="订单状态" clearable style="width: 140px">
          <el-option label="全部" :value="undefined" />
          <el-option label="待付款" :value="1" />
          <el-option label="已付款" :value="2" />
          <el-option label="已发货" :value="3" />
          <el-option label="已完成" :value="4" />
          <el-option label="已取消" :value="5" />
        </el-select>
        <el-button type="primary" @click="fetchList">筛选</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>

      <!-- 新建/编辑订单弹窗 -->
      <el-dialog v-model="editDialog" :title="editMode === 'add' ? '新建订单' : '编辑订单'" width="500px">
        <el-form :model="editForm" label-width="90px">
          <el-form-item label="收货人">
            <el-input v-model="editForm.receiverName" />
          </el-form-item>
          <el-form-item label="收货电话">
            <el-input v-model="editForm.receiverPhone" />
          </el-form-item>
          <el-form-item label="收货地址">
            <el-input v-model="editForm.receiverAddress" />
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="editForm.remark" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="editDialog = false">取消</el-button>
          <el-button type="primary" @click="handleSaveOrder">保存</el-button>
        </template>
      </el-dialog>
      <el-table :data="orderList" border style="width: 100%" @row-click="handleRowClick">
        <el-table-column prop="orderId" label="ID" width="80" />
        <el-table-column prop="orderNo" label="订单号" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 1">待付款</el-tag>
            <el-tag v-else-if="scope.row.status === 2" type="warning">已付款</el-tag>
            <el-tag v-else-if="scope.row.status === 3" type="info">已发货</el-tag>
            <el-tag v-else-if="scope.row.status === 4" type="success">已完成</el-tag>
            <el-tag v-else-if="scope.row.status === 5" type="info">已取消</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220">
          <template #default="scope">
            <el-button size="small" @click.stop="showDetail(scope.row)">详情</el-button>
            <el-button size="small" type="danger" @click.stop="handleDelete(scope.row)" v-if="scope.row.status !== 5">删除</el-button>
            <el-button size="small" type="warning" @click.stop="handleCancel(scope.row)" v-if="scope.row.status === 1">取消</el-button>
            <el-button size="small" type="success" @click.stop="handleConfirm(scope.row)" v-if="scope.row.status === 3">确认收货</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 16px; text-align: right;">
        <el-pagination
          background
          layout="prev, pager, next, jumper, ->, total"
          :total="total"
          :page-size="pageSize"
          :current-page="pageNum"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 订单详情弹窗 -->
    <el-dialog v-model="detailDialog" title="订单详情" width="600px">
      <el-descriptions :column="2" border v-if="detail">
        <el-descriptions-item label="订单号">{{ detail.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag v-if="detail.status === 1">待付款</el-tag>
          <el-tag v-else-if="detail.status === 2" type="warning">已付款</el-tag>
          <el-tag v-else-if="detail.status === 3" type="info">已发货</el-tag>
          <el-tag v-else-if="detail.status === 4" type="success">已完成</el-tag>
          <el-tag v-else-if="detail.status === 5" type="info">已取消</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="收货人">{{ detail.receiverName }}</el-descriptions-item>
        <el-descriptions-item label="收货电话">{{ detail.receiverPhone }}</el-descriptions-item>
        <el-descriptions-item label="收货地址" :span="2">{{ detail.receiverAddress }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ detail.remark }}</el-descriptions-item>
        <el-descriptions-item label="总金额">{{ detail.totalAmount }}</el-descriptions-item>
        <el-descriptions-item label="实付金额">{{ detail.paymentAmount }}</el-descriptions-item>
      </el-descriptions>
      <div style="margin: 16px 0 8px 0;"><b>订单商品</b></div>
      <el-table :data="detail.items || []" border size="small">
        <el-table-column prop="productName" label="商品名" />
        <el-table-column prop="productImage" label="图片" width="60">
          <template #default="scope">
            <el-image v-if="scope.row.productImage" :src="scope.row.productImage" style="width:40px;height:40px" fit="cover" />
          </template>
        </el-table-column>
        <el-table-column prop="price" label="单价" width="80" />
        <el-table-column prop="quantity" label="数量" width="60" />
        <el-table-column prop="totalPrice" label="总价" width="100" />
      </el-table>
      <template #footer>
        <el-button @click="detailDialog = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { getAdminOrderList, getAdminOrderDetail, addAdminOrder, updateAdminOrder, deleteAdminOrder } from '../api/order'
import { ElMessage, ElMessageBox } from 'element-plus'

const orderList = ref([])
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)
const search = reactive({
  status: undefined
})

const detailDialog = ref(false)
const detail = ref(null)

const fetchList = async () => {
  try {
    const params = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      status: search.status
    }
    const res = await getAdminOrderList(params)
    // 管理端返回的可能是数组或分页对象，需兼容
    if (Array.isArray(res.data)) {
      orderList.value = res.data
      total.value = res.data.length
    } else if (res.data && res.data.list) {
      orderList.value = res.data.list
      total.value = res.data.total
    }
  } catch (e) {
    ElMessage.error('获取订单列表失败')
  }
}

const handlePageChange = (val) => {
  pageNum.value = val
  fetchList()
}

const resetSearch = () => {
  search.status = undefined
  pageNum.value = 1
  fetchList()
}

const showDetail = async (row) => {
  try {
    const res = await getAdminOrderDetail(row.orderId || row.id)
    if (res.data) {
      detail.value = res.data
      detailDialog.value = true
    }
  } catch (e) {
    ElMessage.error('获取订单详情失败')
  }
}

const handleRowClick = (row) => {
  showDetail(row)
}

const handleCancel = (row) => {
  ElMessageBox.confirm('确定要取消该订单吗？', '提示', { type: 'warning' })
    .then(async () => {
      await cancelOrder(row.orderId)
      ElMessage.success('订单已取消')
      fetchList()
    })
    .catch(() => {})
}

const handleConfirm = (row) => {
  ElMessageBox.confirm('确认收货？', '提示', { type: 'info' })
    .then(async () => {
      await confirmOrder(row.orderId)
      ElMessage.success('已确认收货')
      fetchList()
    })
    .catch(() => {})
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该订单吗？', '警告', { type: 'error' })
    .then(async () => {
      await deleteAdminOrder(row.orderId || row.id)
      ElMessage.success('订单已删除')
      fetchList()
    })
    .catch(() => {})
}

const editDialog = ref(false)
const editMode = ref('add')
const editForm = reactive({
  id: null,
  receiverName: '',
  receiverPhone: '',
  receiverAddress: '',
  remark: ''
})

const openAddDialog = () => {
  editMode.value = 'add'
  Object.assign(editForm, {
    id: null,
    receiverName: '',
    receiverPhone: '',
    receiverAddress: '',
    remark: ''
  })
  editDialog.value = true
}

const handleSaveOrder = async () => {
  // TODO: 调用 addOrder 或 updateOrder，保存订单
  ElMessage.success('保存成功（请补充API调用）')
  editDialog.value = false
}
onMounted(() => {
  fetchList()
})
</script>